package com.service.totalauth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.service.config.constant.ApiUrlConstants;
import com.service.config.utils.DateUtil;
import com.service.config.utils.JsonXMLUtils;
import com.service.config.utils.ModelMapperUtil;
import com.service.config.utils.RedisUtil;
import com.service.totalauth.dto.*;
import com.service.totalauth.entity.Authorization;
import com.service.totalauth.vo.AuthorizationVo;
import com.service.totalauth.vo.QyWeiChatUserDetailVo;
import com.service.totalauth.vo.QyWeiChatUserVo;
import com.service.totalauth.vo.WeiChatVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;

import static com.service.config.constant.ApiUrlConstants.*;
import static com.service.config.utils.DateUtil.getAddDate;
import static com.service.config.utils.DesUtil.decodeUrlToString;
import static com.service.config.utils.DesUtil.encodeUrlToString;

/**
 * @author
 * @version 1.0
 * @date 2021/6/24 8:49
 */
@Service
@Slf4j
public class QueryWeiChatServiceImpl {
    @Resource
    RestTemplate restTemplate;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 拼接微信交互的url
     * @param url
     * @param customerAppId
     * @param customerSecret
     * @return
     */
    public String getUrl(String url, String customerAppId, String customerSecret) {
        url = QY_WEI_XIN_GET_ACCESS_TOKEN.concat(customerAppId).concat(qy_corp_secret).concat(customerSecret);
        return url;
    }
    /**
     * 拼接微信交互的url
     * @param url
     * @param customerAppId
     * @param customerSecret
     * @return
     */
    public String getUrlWenXin(String url, String customerAppId, String customerSecret,String code) {
        url = url.concat(WEI_XIN_CODE2_SESSION+ customerAppId +secret+ customerSecret +js_code+code);
        return url;
    }

    /**
     * 拼接微信交互的url
     * @param url
     * @param customerAppId
     * @param customerSecret
     * @return
     */
    public String getUrlWenXinAccessToken(String url, String customerAppId, String customerSecret) {
        url = url.concat(WEI_XIN_GET_ACCESS_TOKEN+ customerAppId +secret+ customerSecret);
        return url;
    }

    /**
     * 获取微信token
     * @param url
     * @return
     */
    public HashMap getWenXinAccessToken(String url) throws Exception {
        HashMap map = new HashMap();
        HttpEntity<String> requestEntity = new HttpEntity<>("");
        ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, JSONObject.class);
        WeiChatVo weiChatVo = ModelMapperUtil.strictMap(response.getBody(), WeiChatVo.class);
        if (weiChatVo.getErrcode()==null || weiChatVo.getErrcode() == 0) {
            map.put("weiChatVo", JsonXMLUtils.obj2json(weiChatVo));
        }else {
            map.put("errcode",JsonXMLUtils.obj2json(weiChatVo));
        }
        return map;
    }
    /**
     * 获取小程序 scheme 码
     * @param accessToken
     * @return
     */
    public Map<String, Object> getUrlSchemeGenerate(String accessToken, String redisToken,String programmeInfoBindId) throws Exception {
        HttpHeaders httpHeaders = getHttpHeaders();
        WeiChatGetURLScheme weiChatGetURLScheme = new WeiChatGetURLScheme();
        weiChatGetURLScheme.setIs_expire(false);
        Date addDate = getAddDate(new Date(), 1);
        String string = DateUtil.datetoString(addDate);
        string = DateUtil.date2TimeStamp(string, "yyyy-MM-dd HH:mm:ss");
        weiChatGetURLScheme.setExpire_time(Integer.parseInt(string));
        WeiChatJumpWxa weiChatJumpWxa = new WeiChatJumpWxa();
        weiChatJumpWxa.setEnv_version("release");
        weiChatJumpWxa.setPath("pages/wechatCode/index");
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("&redisToken=")
                .append(redisToken).append("&programmeInfoBindId=")
                .append(programmeInfoBindId);
        weiChatJumpWxa.setQuery(stringBuilder.toString());
        weiChatGetURLScheme.setJump_wxa(weiChatJumpWxa);
        Map<String, Object> stringObjectMap = JSONObject.parseObject(JsonXMLUtils.obj2json(weiChatGetURLScheme));
        String s = JsonXMLUtils.obj2json(weiChatGetURLScheme);
        HttpEntity<Map> requestEntity = new HttpEntity<Map>( stringObjectMap,httpHeaders);
        ResponseEntity<JSONObject> response = restTemplate.postForEntity(URL_SCHEME_GENERATE.concat(accessToken),  requestEntity, JSONObject.class);
        WeiChatResponseDto weiChatResponseDto = ModelMapperUtil.strictMap(response.getBody(), WeiChatResponseDto.class);
        if (weiChatResponseDto.getErrcode() == 0) {
            stringObjectMap.put("weiChatResponseDto", JsonXMLUtils.obj2json(weiChatResponseDto));
        }else {
            stringObjectMap.put("errcode",JsonXMLUtils.obj2json(weiChatResponseDto));
        }
        return stringObjectMap;
    }
    /**
     * 获取小程序 scheme 码
     * @param accessToken
     * @return
     */
    public Map<String, Object> getShareUrlSchemeGenerate(String accessToken, String redisToken,String programmeInfoBindId) throws Exception {
        HttpHeaders httpHeaders = getHttpHeaders();
        WeiChatGetURLScheme weiChatGetURLScheme = new WeiChatGetURLScheme();
        weiChatGetURLScheme.setIs_expire(false);
        Date addDate = getAddDate(new Date(), 1);
        String string = DateUtil.datetoString(addDate);
        string = DateUtil.date2TimeStamp(string, "yyyy-MM-dd HH:mm:ss");
        weiChatGetURLScheme.setExpire_time(Integer.parseInt(string));
        WeiChatJumpWxa weiChatJumpWxa = new WeiChatJumpWxa();
        weiChatJumpWxa.setEnv_version("release");
        weiChatJumpWxa.setPath("pages/staffToqy/index");
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("&redisToken=")
                .append(redisToken).append("&programmeInfoBindId=")
                .append(programmeInfoBindId);
        weiChatJumpWxa.setQuery(stringBuilder.toString());
        weiChatGetURLScheme.setJump_wxa(weiChatJumpWxa);
        Map<String, Object> stringObjectMap = JSONObject.parseObject(JsonXMLUtils.obj2json(weiChatGetURLScheme));
        String s = JsonXMLUtils.obj2json(weiChatGetURLScheme);
        HttpEntity<Map> requestEntity = new HttpEntity<Map>( stringObjectMap,httpHeaders);
        ResponseEntity<JSONObject> response = restTemplate.postForEntity(URL_SCHEME_GENERATE.concat(accessToken),  requestEntity, JSONObject.class);
        WeiChatResponseDto weiChatResponseDto = ModelMapperUtil.strictMap(response.getBody(), WeiChatResponseDto.class);
        if (weiChatResponseDto.getErrcode() == 0) {
            stringObjectMap.put("weiChatResponseDto", JsonXMLUtils.obj2json(weiChatResponseDto));
        }else {
            stringObjectMap.put("errcode",JsonXMLUtils.obj2json(weiChatResponseDto));
        }
        return stringObjectMap;
    }
    /**
     * 获取小程序 scheme 码
     * @param accessToken
     * @return
     */
    public Map<String, Object> getUrlSchemeGenerate(String accessToken, AuthorizationDto authorizationDto) throws Exception {
        HttpHeaders httpHeaders = getHttpHeaders();
        WeiChatGetURLScheme weiChatGetURLScheme = new WeiChatGetURLScheme();
        weiChatGetURLScheme.setIs_expire(false);
        Date addDate = getAddDate(new Date(), 1);
        String string = DateUtil.datetoString(addDate);
        string = DateUtil.date2TimeStamp(string, "yyyy-MM-dd HH:mm:ss");
        weiChatGetURLScheme.setExpire_time(Integer.parseInt(string));
        WeiChatJumpWxa weiChatJumpWxa = new WeiChatJumpWxa();
        weiChatJumpWxa.setEnv_version("release");
        weiChatJumpWxa.setPath("pages/index/index");
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("&apmac=")
                .append(authorizationDto.getApmac())
                .append("&uaddress=")
                .append(authorizationDto.getUaddress())
                .append("&umac=")
                .append(authorizationDto.getUmac())
                .append("&nodeIp=")
                .append(authorizationDto.getNodeIp())
                .append("&ssid=")
                .append(encodeUrlToString(authorizationDto.getSsid()))
                .append("&siteId=").append(authorizationDto.getSiteId());
        weiChatJumpWxa.setQuery(stringBuilder.toString());
        weiChatGetURLScheme.setJump_wxa(weiChatJumpWxa);
        Map<String, Object> stringObjectMap = JSONObject.parseObject(JsonXMLUtils.obj2json(weiChatGetURLScheme));
        String s = JsonXMLUtils.obj2json(weiChatGetURLScheme);
        HttpEntity<Map> requestEntity = new HttpEntity<Map>( stringObjectMap,httpHeaders);
        ResponseEntity<JSONObject> response = restTemplate.postForEntity(URL_SCHEME_GENERATE.concat(accessToken),  requestEntity, JSONObject.class);
        WeiChatResponseDto weiChatResponseDto = ModelMapperUtil.strictMap(response.getBody(), WeiChatResponseDto.class);
        if (weiChatResponseDto.getErrcode() == 0) {
            stringObjectMap.put("weiChatResponseDto", JsonXMLUtils.obj2json(weiChatResponseDto));
        }else {
            stringObjectMap.put("errcode",JsonXMLUtils.obj2json(weiChatResponseDto));
        }
        return stringObjectMap;
    }
    /**
     * 与微信服务端交互
     * @param url
     * @return
     */
    public HashMap getOpenId (String url) throws Exception {
        HashMap map = new HashMap();
        HttpEntity<String> requestEntity = new HttpEntity<>("");
        ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, JSONObject.class);
        WeiChatVo weiChatVo = ModelMapperUtil.strictMap(response.getBody(), WeiChatVo.class);
        if (weiChatVo.getErrcode()==null || weiChatVo.getErrcode() == 0) {
            map.put("weiChatDto", JsonXMLUtils.obj2json(weiChatVo));
        }else {
            map.put("errcode",JsonXMLUtils.obj2json(weiChatVo));
        }
        return map;
    }
    /**
     * 与微信服务端交互
     * @param url
     * @return
     */
    public HashMap getWeChatOpenId (String url) throws Exception {
        HashMap map = new HashMap();
        HttpEntity<String> requestEntity = new HttpEntity<>("");
        ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, JSONObject.class);
        WeiChatDto weiChatDto = ModelMapperUtil.strictMap(response.getBody(), WeiChatDto.class);
        if (weiChatDto.getErrcode()==null || weiChatDto.getErrcode().equals("0")) {
            map.put("weiChatDto", JsonXMLUtils.obj2json(weiChatDto));
        }else {
            map.put("errcode",JsonXMLUtils.obj2json(weiChatDto));
        }
        return map;
    }
    public HashMap getUserInfo(String access_token, String code) throws Exception {
        String url = code2Session.concat(access_token).concat(js_code).concat(code);
        HashMap map = new HashMap();
        HttpEntity<String> requestEntity = new HttpEntity<>("");
        ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, JSONObject.class);
        QyWeiChatUserVo qyWeiChatUserVo = ModelMapperUtil.strictMap(response.getBody(), QyWeiChatUserVo.class);
        if (qyWeiChatUserVo.getErrcode() == null || qyWeiChatUserVo.getErrcode() == 0) {
            map.put("qyWeiChatUserVo", JsonXMLUtils.obj2json(qyWeiChatUserVo));
        }else {
            map.put("errcode",JsonXMLUtils.obj2json(qyWeiChatUserVo));
        }
        return map;
    }
    public HashMap getUser(String access_token, String userId) throws Exception {
        String url = getUser.concat(access_token).concat(getUserId).concat(userId);
        HashMap map = new HashMap();
        HttpEntity<String> requestEntity = new HttpEntity<>("");
        ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, JSONObject.class);
        QyWeiChatUserDetailVo qyWeiChatUserDetailVo = ModelMapperUtil.strictMap(response.getBody(), QyWeiChatUserDetailVo.class);
        if (qyWeiChatUserDetailVo.getErrcode() == null || qyWeiChatUserDetailVo.getErrcode() == 0) {
            map.put("qyWeiChatUserDetailVo", JsonXMLUtils.obj2json(qyWeiChatUserDetailVo));
        }else {
            map.put("errcode",JsonXMLUtils.obj2json(qyWeiChatUserDetailVo));
        }
        return map;
    }
    /**
     * 获取token_id
     * @param username
     * @param password
     * @param requestHeaders
     * @return
     */
    public HttpHeaders getToken(String username, String password, String domain, HttpHeaders requestHeaders) {
        String token = "";
        if (redisUtil.exist(username.concat("token"))) {
            token = redisUtil.getValue(username.concat("token"));
            requestHeaders.add("X-AUTH-TOKEN", token);
            requestHeaders.add("Accept-Language", "en-US");
            return requestHeaders ;
        } else {
            try {
                Map map = new HashMap();
                map.put("userName", username);
                map.put("password", password);
                HttpEntity<Map> requestEntity = new HttpEntity<Map>(map, requestHeaders);
                ResponseEntity<JSONObject> response = restTemplate.postForEntity(URL_FIRST.concat(domain).concat(ApiUrlConstants.CLOUD_CAMPUS_TOKEN_URL), requestEntity, JSONObject.class);
                JSONObject jsonObject = response.getBody().getJSONObject("data");
                token = jsonObject.get("token_id").toString();
                redisUtil.set(username.concat("token"),1,token,10);
                requestHeaders.add("X-AUTH-TOKEN",token);
                requestHeaders.add("Accept-Language", "en-US");
                return requestHeaders;
            }catch (Exception e) {
                return null;
            }
        }
    }
    /**
     * 授权终端用户
     * @param requestHeaders
     * @param authorizationVo
     * @return
     * @throws Exception
     */

    public String setAuthorizationUser(HttpHeaders requestHeaders,String domain, AuthorizationVo authorizationVo) throws Exception {
        try {
            Map map = new HashMap();
            Authorization authorizationUser = new Authorization();
            authorizationUser.setDeviceMac(authorizationVo.getApmac());
            String ssid = authorizationVo.getSsid();
            System.out.println("authorizationUser.getSsid()1"+ssid);
            for (int i = 0 ;i< 20; i++) {
                ssid = decodeUrlToString(ssid);
            }
            if (ssid.contains(" ")) {
                ssid = ssid.replaceAll(" ","+");
            }
            authorizationUser.setSsid(ssid);
            System.out.println("authorizationUser.getSsid()"+ssid);
            authorizationUser.setTerminalIpV4(authorizationVo.getUaddress());
            if (authorizationVo.getNodeIp() != null) {
                authorizationUser.setNodeIp(authorizationVo.getNodeIp());
            }
            authorizationUser.setTerminalMac(authorizationVo.getUmac());
            if (authorizationVo.getUserName() != null && !"".equals(authorizationVo.getUserName())) {
                authorizationUser.setUserName(authorizationVo.getUserName());
            }
            map = JSONObject.parseObject(JsonXMLUtils.obj2json(authorizationUser));
            HttpEntity<Map> requestEntity = new HttpEntity<Map>(map, requestHeaders);
            ResponseEntity<JSONObject> response = restTemplate.postForEntity(URL_FIRST.concat(domain).concat(ApiUrlConstants.AUTHORIZATION_URL), requestEntity, JSONObject.class);
            JSONObject jsonObject = response.getBody();
            return jsonObject.getString("psessionid");
        }catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }
    public HttpHeaders getHttpHeaders() {
        HttpHeaders requestHeaders = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        requestHeaders.setContentType(type);
        requestHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());
        return requestHeaders;
    }

    public Map<String, Object> getPhoneNumber(String accessToken, String code) throws Exception {
        Map<String, Object> stringObjectMap = new HashMap<>();
        stringObjectMap.put("code",code);
        HttpEntity<Map> requestEntity = new HttpEntity<Map>( stringObjectMap);
        ResponseEntity<JSONObject> response = restTemplate.postForEntity(GET_PHONE_NUMBER.concat(accessToken),  requestEntity, JSONObject.class);
        PhoneNumber phoneNumber = ModelMapperUtil.strictMap(response.getBody(), PhoneNumber.class);
        if (phoneNumber.getErrcode() == 0) {
            stringObjectMap.put("phoneNumber", JsonXMLUtils.obj2json(phoneNumber));
        }else {
            stringObjectMap.put("errcode",JsonXMLUtils.obj2json(phoneNumber));
        }
        return stringObjectMap;
    }
}
